//
//  YKHTTPSignatureManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "YKHTTPSignatureManager.h"
#import "../../Utils/Encryption/IMEncryptUtils.h"
#import "../../Utils/Logger/IMLogUtils.h"

@implementation YKHTTPSignatureManager

+ (NSDictionary *)signParameters:(NSDictionary *)parameters withKey:(NSString *)signKey {
    if (!parameters || !signKey || signKey.length == 0) {
        return parameters ?: @{};
    }

    // 简化版签名实现 - 回退到串联功能之前的版本
    // 1. 获取所有参数键并排序
    NSArray *sortedKeys = [[parameters allKeys] sortedArrayUsingSelector:@selector(compare:)];

    // 2. 构建参数字符串
    NSMutableArray *paramPairs = [NSMutableArray array];
    for (NSString *key in sortedKeys) {
        id value = parameters[key];
        NSString *valueString = @"";
        
        if ([value isKindOfClass:[NSString class]]) {
            valueString = value;
        } else if ([value isKindOfClass:[NSNumber class]]) {
            valueString = [value stringValue];
        } else if (value != nil && ![value isKindOfClass:[NSNull class]]) {
            valueString = [NSString stringWithFormat:@"%@", value];
        }
        
        [paramPairs addObject:[NSString stringWithFormat:@"%@=%@", key, valueString]];
    }

    // 3. 拼接参数字符串
    NSString *paramString = [paramPairs componentsJoinedByString:@"&"];
    
    // 4. 添加签名密钥
    NSString *signString = [NSString stringWithFormat:@"%@&key=%@", paramString, signKey];
    
    // 5. 生成MD5签名
    NSString *sign = [[IMEncryptUtils md5:signString] lowercaseString];
    
    // 6. 添加签名到参数中
    NSMutableDictionary *finalParams = [parameters mutableCopy];
    finalParams[@"sign"] = sign;
    
    [IMLogUtils debug:IMLogTagNetwork format:@"[签名调试] 参数字符串: %@", paramString];
    [IMLogUtils debug:IMLogTagNetwork format:@"[签名调试] 签名字符串: %@", signString];
    [IMLogUtils debug:IMLogTagNetwork format:@"[签名调试] 生成签名: %@", sign];
    
    return [finalParams copy];
}


// 字符串化工具（支持NSNull、NSNumber、NSURL、BOOL等）
+ (NSString *)im_stringFromValue:(id)value {
    if (!value || [value isKindOfClass:[NSNull class]]) return @"";
    if ([value isKindOfClass:[NSString class]]) return value;
    if ([value isKindOfClass:[NSNumber class]]) return [value stringValue];
    if ([value isKindOfClass:[NSURL class]])    return [(NSURL *)value absoluteString];
    if ([value isKindOfClass:[NSDate class]])   return [NSString stringWithFormat:@"%@", value];
    // 如果你有特殊对象需要自定义
    return [NSString stringWithFormat:@"%@", value];
}

+ (NSDictionary *)addCommonParameters:(NSDictionary *)parameters
                          gameVersion:(NSString *)gameVersion
                           sdkVersion:(NSString *)sdkVersion
                             timezone:(NSString *)timezone {
    
    NSMutableDictionary *mutableParams = [parameters mutableCopy] ?: [NSMutableDictionary dictionary];
    
    // 添加公共参数
    mutableParams[@"ts"] = @((NSInteger)[[NSDate date] timeIntervalSince1970]);
    
    if (gameVersion && gameVersion.length > 0) {
        mutableParams[@"ver"] = gameVersion;
    }
    
    if (sdkVersion && sdkVersion.length > 0) {
        mutableParams[@"sdk_ver"] = sdkVersion;
    }
    
    if (timezone && timezone.length > 0) {
        mutableParams[@"tz"] = timezone;
    }
    
    return [mutableParams copy];
}

+ (NSDictionary *)buildRequestParameters:(NSDictionary *)parameters
                                 signKey:(NSString *)signKey
                             gameVersion:(NSString *)gameVersion
                              sdkVersion:(NSString *)sdkVersion
                                timezone:(NSString *)timezone {
    
    // 1. 添加公共参数
    NSDictionary *paramsWithCommon = [self addCommonParameters:parameters
                                                    gameVersion:gameVersion
                                                     sdkVersion:sdkVersion
                                                       timezone:timezone];
    
    // 2. 生成签名
    NSDictionary *finalParams = [self signParameters:paramsWithCommon withKey:signKey];
    
    [IMLogUtils debug:IMLogTagNetwork format:@"[YKHTTPSignature] 最终请求参数: %@", finalParams];
    
    return finalParams;
}

+ (NSString *)generatePostmanParametersWithOriginalParams:(NSDictionary *)parameters
                                                  signKey:(NSString *)signKey
                                              gameVersion:(NSString *)gameVersion
                                               sdkVersion:(NSString *)sdkVersion
                                                 timezone:(NSString *)timezone {
    
    NSDictionary *finalParams = [self buildRequestParameters:parameters
                                                     signKey:signKey
                                                 gameVersion:gameVersion
                                                  sdkVersion:sdkVersion
                                                    timezone:timezone];
    
    NSMutableArray *postmanParams = [NSMutableArray array];
    for (NSString *key in finalParams) {
        id value = finalParams[key];
        NSString *valueString = [self im_stringFromValue:value];
        [postmanParams addObject:[NSString stringWithFormat:@"%@:%@", key, valueString]];
    }
    
    return [postmanParams componentsJoinedByString:@"\n"];
}

#pragma mark - Private Methods

+ (NSString *)stringFromValue:(id)value {
    if ([value isKindOfClass:[NSString class]]) {
        return value;
    } else if ([value isKindOfClass:[NSNumber class]]) {
        return [value stringValue];
    } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
        // 对于复杂对象，转换为JSON字符串
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:0 error:&error];
        if (!error && jsonData) {
            return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
    }
    
    // 默认返回对象的描述
    return [value description] ?: @"";
}

@end
